package com.hbsoft.wechat.service.impl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hb.bean.CallResult;
import com.hb.gsonAdapter.DateDefaultAdapter;
import com.hb.gsonAdapter.DoubleDefaultAdapter;
import com.hb.gsonAdapter.IntegerDefaultAdapter;
import com.hb.gsonAdapter.LongDefaultAdapter;
import com.hb.util.HttpUtil;
import com.hb.util.StringUtil;
import com.hbsoft.common.constant.Constant;
import com.hbsoft.util.GsonUtil;
import com.hbsoft.util.WechatUtil;
import com.hbsoft.wechat.bean.*;
import com.hbsoft.wechat.dao.OtherYYPDao;
import com.hbsoft.wechat.dao.service.SwanAdminDaoService;
import com.hbsoft.wechat.dao.service.SwanDaoService;
import com.hbsoft.wechat.dao.service.SwanLogDaoService;
import com.hbsoft.wechat.service.HBUserService;
import com.hbsoft.wechat.service.SwanService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("swanService")
public class SwanServiceImpl implements SwanService {
    public final Gson gson = new GsonBuilder().registerTypeAdapter(Integer.class, new IntegerDefaultAdapter())
            .registerTypeAdapter(Double.class, new DoubleDefaultAdapter())
            .registerTypeAdapter(Long.class, new LongDefaultAdapter())
            .registerTypeAdapter(Date.class, new DateDefaultAdapter()).setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    private SwanDaoService swanDaoService;
    private SwanAdminDaoService swanAdminDaoService;
    private SwanLogDaoService swanLogDaoService;
    private OtherYYPDao otherYYPDao;
    private WechatUtil wechatUtil;
    private HBUserService hbUserService;

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    public SwanServiceImpl(SwanDaoService swanDaoService, SwanAdminDaoService swanAdminDaoService, SwanLogDaoService swanLogDaoService, OtherYYPDao otherYYPDao, WechatUtil wechatUtil, HBUserService hbUserService) {
        this.swanDaoService = swanDaoService;
        this.swanAdminDaoService = swanAdminDaoService;
        this.swanLogDaoService = swanLogDaoService;
        this.otherYYPDao = otherYYPDao;
        this.wechatUtil = wechatUtil;
        this.hbUserService = hbUserService;
    }

    @Override
    public CallResult<String> addSwan(Swan swan) throws Exception {
        CallResult<String> result = new CallResult<>();
        String openId = swan.getOpenId();
        Swan swanName = new Swan();
        swanName.setOpenId(openId);
        swanName.setName(swan.getName());
        List<Swan> all = swanDaoService.getAll(swanName);
        if (all.size() > 0) {
            result.setCode(400);
            result.setMsg("您已创建过该名称的卡口");
        } else {
            swanDaoService.add(swan);

            hbUserService.addHBUser(swan.getPhone(), 120, swan.getUserName());

            result.setCode(0);
            result.setMsg("创建卡口成功");
        }
        return result;
    }

    @Override
    public CallResult<String> addSwanAdmin(String HealthCode, WXUser wxUser) throws Exception {
        CallResult<String> result = new CallResult<>();
        Swan swan = new Swan();
        swan.setHealthCode(HealthCode);
        Swan byField = swanDaoService.getByField(swan);
        if (byField == null) {
            result.setCode(400);
            result.setMsg("未找到卡口信息");
        } else {
            SwanAdmin swanAdmin = new SwanAdmin();
            swanAdmin.setSwanId(byField.getId_prikey());
            swanAdmin.setOpenId(wxUser.getOpenid());
            List<SwanAdmin> all = swanAdminDaoService.getAll(swanAdmin);
            if (all != null && all.size() == 0) {
                swanAdminDaoService.add(swanAdmin);
                result.setCode(0);
                result.setMsg("加入卡口成功");
                result.setData(byField.getId_prikey() + "");
            } else {
                result.setCode(0);
                result.setMsg("加入卡口成功");
                result.setData(byField.getId_prikey() + "");
            }
        }
        return result;
    }

    @Override
    public CallResult<String> addSwanLog(SwanLog swanLog) throws Exception {
        CallResult<String> result = new CallResult<>();
        Integer integer = swanLogDaoService.addPrikey(swanLog);
        try {
            Swan swan = swanDaoService.getById(swanLog.getSwanId());
            if(swan == null){
                result.setCode(400);
                result.setMsg("SwanId参数有误");
                return result;
            }
            result.setData(GsonUtil.toJson(swan));
            Map<String, Object> param = new HashMap<>();
            param.put("groupId", swanLog.getSwanId());
            swanLog.setId_prikey(integer);
            String data = gson.toJson(swanLog);
            param.put("msg", data);
            HttpUtil.sendPost("http://web.vfpbs.cn/api/broadcast", param);

        } catch (Exception e) {
            logger.info(e.getMessage(),e);
            e.printStackTrace();
        }
        result.setCode(0);
        result.setMsg("添加成功");
        return result;
    }

    @Override
    public Map<String, Object> getPagingSwanLog(SwanLog swanLog) throws Exception {
        return swanLogDaoService.getPagingData(swanLog);
    }

    @Override
    public CallResult<Map<String, Object>> getSwanName(String qrCode, WXUser wxUser) throws Exception {
        CallResult<Map<String, Object>> result = new CallResult<>();
        Swan swan = new Swan();
        swan.setQrCode(qrCode);
        Swan byField = swanDaoService.getByField(swan);
        if (byField == null) {
            result.setCode(400);
            result.setMsg("未找到卡口信息");
        } else {
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("swan", byField);
            if (wxUser != null) {
                SwanAdmin swanAdmin = new SwanAdmin();
                swanAdmin.setSwanId(byField.getId_prikey());
                swanAdmin.setOpenId(wxUser.getOpenid());
                List<SwanAdmin> all = swanAdminDaoService.getAll(swanAdmin);
                if (all.size() > 0) {
                    data.put("adminFlag", 1);
                    data.put("adminUser", all.get(0));
                } else {
                    data.put("adminFlag", 0);
                }
                SwanLog userLastSwanLog = otherYYPDao.findUserLastSwanLog(byField.getId_prikey(), wxUser.getOpenid());
                data.put("swanLog", userLastSwanLog);
            }
            result.setCode(0);
            result.setMsg("获取成功");
            result.setData(data);
        }
        return result;
    }

    @Override
    public CallResult<Swan> getSwanCode(Integer id_prikey) throws Exception {
        CallResult<Swan> result = new CallResult<>();
        Swan byId = swanDaoService.getById(id_prikey);
        if (byId == null) {
            result.setCode(400);
            result.setMsg("未找到卡口信息");
        } else {
            String qrCode = byId.getQrCode();
            Swan swanQrCode = new Swan();
            if (StringUtil.isEmpty(qrCode)) {
                while (true) {
                    String s = StringUtil.randomNumId(6);
                    String code = s.substring(s.length() - 6);
                    code = code.replace("4", "0");
                    Swan swan = new Swan();
                    swan.setQrCode(code);
                    List<Swan> all = swanDaoService.getAll(swan);
                    if (all.size() == 0) {
                        qrCode = code;
                        break;
                    }
                }
                String qrCodeUrl = "";
                if(Constant.qrCodetype_bus.equals(byId.getType())){
                    qrCodeUrl = wechatUtil.getWxAappQrCode("gg_" + qrCode);
                }else{
                    qrCodeUrl = wechatUtil.getWxAappQrCode("kk_" + qrCode);
                }
                swanQrCode.setId_prikey(id_prikey);
                swanQrCode.setQrCode(qrCode);
                swanQrCode.setQrCodeUrl(qrCodeUrl);
                swanDaoService.set(swanQrCode);
                result.setCode(0);
                result.setMessage("获取成功");
                swanQrCode.setId_prikey(null);
                result.setData(swanQrCode);
            } else {
                swanQrCode.setQrCode(byId.getQrCode());
                swanQrCode.setQrCodeUrl(byId.getQrCodeUrl());
            }
            result.setCode(0);
            result.setMessage("获取成功");
            result.setData(swanQrCode);
        }
        return result;
    }

    @Override
    public CallResult<List<Map<String, Object>>> getSwanDeptName(Integer id_prikey, String deptName) throws Exception {
        CallResult<List<Map<String, Object>>> result = new CallResult<>();
        List<Map<String, Object>> list = otherYYPDao.findSwanDeptName(id_prikey, deptName);
        result.setCode(0);
        result.setMessage("获取成功");
        result.setData(list);
        return result;
    }

    @Override
    public CallResult<Swan> getSwanAdminCode(Integer id_prikey) throws Exception {
        CallResult<Swan> result = new CallResult<>();
        Swan byId = swanDaoService.getById(id_prikey);
        if (byId == null) {
            result.setCode(400);
            result.setMsg("未找到卡口信息");
        } else {
            String healthCode = byId.getHealthCode();
            Swan swanhealthCode = new Swan();
            if (StringUtil.isEmpty(healthCode)) {
                while (true) {
                    String s = StringUtil.randomNumId(6);
                    String code = s.substring(s.length() - 6);
                    code = code.replace("4", "0");
                    Swan swan = new Swan();
                    swan.setHealthCode(code);
                    List<Swan> all = swanDaoService.getAll(swan);
                    if (all.size() == 0) {
                        healthCode = code;
                        break;
                    }
                }
                String healthCodeUrl = wechatUtil.getWxAappQrCode("mw_" + healthCode);
                swanhealthCode.setId_prikey(id_prikey);
                swanhealthCode.setHealthCode(healthCode);
                swanhealthCode.setHealthCodeUrl(healthCodeUrl);
                swanDaoService.set(swanhealthCode);
                result.setCode(0);
                result.setMessage("获取成功");
                swanhealthCode.setId_prikey(null);
                result.setData(swanhealthCode);
            } else {
                swanhealthCode.setHealthCode(byId.getHealthCode());
                swanhealthCode.setHealthCodeUrl(byId.getHealthCodeUrl());
            }
            result.setCode(0);
            result.setMessage("获取成功");
            result.setData(swanhealthCode);
        }
        return result;
    }

    @Override
    public CallResult<List<Swan>> getMySwanAll(String openId) throws Exception {
        CallResult<List<Swan>> result = new CallResult<>();
        Swan swan = new Swan();
        swan.setOpenId(openId);
        List<Swan> all = swanDaoService.getAll(swan);
        result.setCode(0);
        result.setMsg("获取成功");
        result.setData(all);
        return result;
    }

    @Override
    public CallResult<String> setSwan(Swan swan) throws Exception {
        CallResult<String> result = new CallResult<>();
        swanDaoService.set(swan);
        result.setCode(0);
        result.setMsg("修改成功");
        return result;
    }

    @Override
    public CallResult<Map<String, Object>> getSwanById(Integer id_prikey) throws Exception {
        CallResult<Map<String, Object>> result = new CallResult<>();
        Swan byId = swanDaoService.getById(id_prikey);
        if (byId == null) {
            result.setCode(400);
            result.setMsg("未找到卡口信息");
        } else {
            Map<String, Object> data = new HashMap<>();
            data.put("swan", byId);
            SwanAdmin swanAdmin = new SwanAdmin();
            swanAdmin.setSwanId(byId.getId_prikey());
            List<SwanAdmin> all = swanAdminDaoService.getAll(swanAdmin);
            data.put("swanAdmin", all);
            result.setCode(0);
            result.setMsg("获取成功");
            result.setData(data);
        }
        return result;
    }

    @Override
    public CallResult<String> removeSwanAdmin(Integer id_prikey) throws Exception {
        CallResult<String> result = new CallResult<>();
        swanAdminDaoService.removeOne(id_prikey);
        result.setCode(400);
        result.setMsg("删除成功");
        return result;
    }
}
